package android.support.v4.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;

import com.kikt.library.R;

/**
 * Created by CaiJL on 2016/6/28.
 */
public class AutoScrollViewPager extends ViewPager {
    private final Context mContext;
    protected OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Log.d("AutoScrollViewPager", "position:" + position);
            handler.removeCallbacksAndMessages(null);
            handler.sendEmptyMessageDelayed(AUTO_SCROLL, scrollDelay);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            handler.removeCallbacksAndMessages(null);
            switch (state) {
                case ViewPager.SCROLL_STATE_DRAGGING:
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    handler.sendEmptyMessageDelayed(AUTO_SCROLL, scrollDelay);
                    break;

            }
        }
    };

    private static final int START = 1;
    private static final int STOP = 2;
    private static final int AUTO_SCROLL = 3;
    private long scrollDelay = 5000;

    private boolean enableAutoScroll;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START:
                    enableAutoScroll = true;
                    removeCallbacksAndMessages(null);
                    sendEmptyMessageDelayed(AUTO_SCROLL, scrollDelay);
                    break;
                case STOP:
                    enableAutoScroll = false;
                    removeCallbacksAndMessages(null);
                    break;
                case AUTO_SCROLL:
                    removeCallbacksAndMessages(null);
                    autoScroll();
                    sendEmptyMessageDelayed(AUTO_SCROLL, scrollDelay);
                    break;
            }
        }

        private void autoScroll() {
            if (getAdapter() == null && !enableAutoScroll) {
                return;
            }
            int currentItem = getCurrentItem();
            int count = getAdapter().getCount();
            if (currentItem == count - 1) {
                setCurrentItem(0, false);
            } else {
                setCurrentItem(currentItem + 1, true);
            }
        }
    };

    protected PagerAdapter adapter;
    protected AutoScrollObserver observer;

    public AutoScrollViewPager(Context context) {
        this(context, null);
    }

    public AutoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        startAutoScroll();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        endAutoScroll();
    }

    private void init(AttributeSet attrs) {
        TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.AutoScrollViewPager);
        scrollDelay = array.getInteger(R.styleable.AutoScrollViewPager_autoScrollDelay, 5000);
        array.recycle();
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
        if (adapter != null) {
            startAutoScroll();
        }
    }

    private class AutoScrollObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            super.onChanged();
            int count = getAdapter().getCount();
            if (count > 0) {
                Log.d("AutoScrollObserver", "count:" + count);
            }
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
            Log.d("AutoScrollObserver", "onInvalidated() called with: " + "");
        }
    }

    private void startAutoScroll() {
        adapter = getAdapter();
        removeOnPageChangeListener(onPageChangeListener);
        addOnPageChangeListener(onPageChangeListener);
        handler.sendEmptyMessage(START);
        if (adapter != null) {
            observer = new AutoScrollObserver();
            adapter.registerDataSetObserver(observer);
        }
    }

    private void endAutoScroll() {
        removeOnPageChangeListener(onPageChangeListener);
        handler.sendEmptyMessage(STOP);
        if (getAdapter() != null) {
            try {
                adapter.unregisterDataSetObserver(observer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 动态设置滚动的时间
     * @param scrollDelay 滚动时间
     */
    public void setScrollDelay(long scrollDelay) {
        this.scrollDelay = scrollDelay;
    }
}
